package com.monolithiot.cdn.management.controller;

import com.monolithiot.cdn.management.common.entity.User;
import com.monolithiot.cdn.management.common.util.SessionStorageUtil;
import com.monolithiot.cdn.management.common.vo.BasicJsonResult;
import com.monolithiot.cdn.management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 2018/11/18 Create by 郭文梁
 * UserController
 * 用户数据访问控制器
 *
 * @author 郭文梁
 * @date 2018/11/18
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 所有用户
     *
     * @return User Entity List
     */
    @GetMapping("/list")
    public List<User> list() {
        return userService.list();
    }

    @PostMapping("/_login")
    public BasicJsonResult<User> login(User user, HttpSession session) {
        User res = userService.login(user);
        if (res == null) {
            return BasicJsonResult.error(1, "用户名或密码错误");
        } else {
            SessionStorageUtil.save(session, res);
            return BasicJsonResult.ok(res);
        }
    }

    /**
     * 用户注册
     *
     * @param user 用户信息
     * @return BJR with User entity
     */
    @PostMapping("/_register")
    public BasicJsonResult<User> register(User user) {
        user.setId(null);
        user.setRole(null);

        User res = userService.register(user);
        return BasicJsonResult.ok(res);
    }
}
